<template>
  <div class="active-comments">
    <div class="event-main">
      <!--                    index从0开始计算-->
      <div class="event-head" v-for="(item, index) in actionShowItems" :key="index">
        <!--非数组，且是评论的记录-->
        <div v-if="!(typeof item == 'object' && item.constructor === Array) &&item.action === 'commented'">
          <div v-if="item.action === 'commented'" class="commented-item">
            <div class="item-info">
              <span :class="'avatar headportrait '+$util.getColorByPersonName(item.actortext ? item.actortext : '')" v-if="item.actortext">
                {{
                  item.actortext.length > 1
                    ? item.actortext.substring(
                        item.actortext.length - 1,
                        item.actortext.length
                      )
                    : item.actortext
                }}
              </span>

              <div class="item-richtext" v-show="isCommentedItemEdit[index]">
                <app-richtexteditor-comment :value="item.comment" :data="JSON.stringify({ data: '1' })" :ref="'actionRichTextEditor' + index" :height="266" name="discuss" :uploadparams="{ objecttype: 'task', version: 'editor' }" :exportparams="{ objecttype: 'task', version: 'editor' }" style="">
                </app-richtexteditor-comment>
                <v-btn class="save" color="cyan darken-1 " @click="itemRichTextClick('save', index, item.comment)">保存
                </v-btn>
                <v-btn class="cancel" color="grey" @click="itemRichTextClick('cancel')">取消</v-btn>
              </div>

              <div class="info-action" v-show="!isCommentedItemEdit[index]">
                <div class="commented-info">
                  <span class="event-actor"><a class="link-member" data-stack="true">{{
                      item.actortext
                    }}</a></span>
                  <a class="event-created-at">{{ item.date }}</a>
                </div>

                <!-- 暂时不要编辑删除操作action-->
                <div class="commented-action" v-if="false">
                  <div class="info-menu">
                    <el-dropdown trigger="click" @command="handleCommand">
                      <span class="el-dropdown-link">
                        <v-btn icon>
                          <v-icon>mdi-dots-horizontal</v-icon>
                        </v-btn>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="edit" :index="index">编辑
                        </el-dropdown-item>
                        <el-dropdown-item command="remove">删除</el-dropdown-item>
                        <el-dropdown-item command="notificationRecord">通知记录
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </div>
                </div>
              </div>
            </div>

            <div v-show="!isCommentedItemEdit[index]" class="commented-comment" v-html="item.comment"></div>
          </div>
        </div>

        <!--非数组，且非评论的记录-->
        <div v-if="!(typeof item == 'object' && item.constructor === Array) && item.action !== 'commented'">
          <div v-if="item.action !== 'commented'" class="action-item">
              <!-- 创建-->
              <v-icon middle color="green lighten-1" style="margin-right: 10px;margin-left: 5px" v-if="
                  item.action === 'created' || item.action === 'opened'
                ">fa-plus-square-o</v-icon>
              <!-- 删除/取消-->
              <v-icon middle color="red lighten-1" style="margin-right: 10px;margin-left: 5px" v-else-if="
                  item.action === 'erased' ||
                    item.action === 'deleted' ||
                    item.action === 'deletedfile' ||
                    item.action === 'canceled' ||
                    item.action === 'closed'
                ">fa-remove</v-icon>
              <!-- 开始/继续-->
              <v-icon middle color="teal darken-1" style="margin-right: 10px;margin-left: 5px" v-else-if="item.action === 'started'|| item.action === 'restarted'">fa fa-play-circle-o</v-icon>
              <!-- 激活-->
              <v-icon middle color="green" style="margin-right: 10px;margin-left: 5px" v-else-if="item.action === 'activated'">fa fa-arrows</v-icon>
              <!-- 指派-->
              <v-icon middle color="teal lighten-1" style="margin-right: 10px;margin-left: 5px" v-else-if="item.action === 'assigned'">fa fa-location-arrow</v-icon>
              <!-- 暂停-->
              <v-icon middle color="deep-purple darken-1" style="margin-right: 10px;margin-left: 5px" v-else-if="item.action === 'paused'">fa-pause-circle-o</v-icon>
              <!-- 完成-->
              <v-icon middle color="green lighten-1" style="margin-right: 10px;margin-left: 5px" v-else-if="item.action === 'finished'">fa-recycle</v-icon>
              <!-- 其他-->
              <v-icon middle color="light-blue darken-1" style="margin-right: 10px;margin-left: 5px" v-else>fa-edit</v-icon>

            <a class="event-created-at">{{ item.date }}</a>
            <span class="event-actor">
              <a class="link-member" data-stack="true">{{ item.actortext }}</a>
            </span>
            <!--            <span class="event-action">{{ getActionText(item.action) }}</span>-->
            <span class="event-action">{{ item.actiontext }}</span>

            <span v-show="
                index + 1 <= actionShowItems.length &&
                  typeof actionShowItems[index + 1] == 'object' &&
                    actionShowItems[index + 1].constructor === Array
              ">
              <a @click="showMoreAction(index + 1)" v-show="!isShowMoreAction[index + 1]">（查看更多动态）</a>
            </span>
          </div>
        </div>

        <!--数组，且非评论的记录-->
        <div v-if="typeof item == 'object' && item.constructor === Array">
          <div class="event-head" v-for="(itemCh, indexCh) in item" v-show="isShowMoreAction[index]" :key="indexCh">
            <div v-if="itemCh.action !== 'commented'" class="action-item">
              <!-- 创建-->
              <v-icon middle color="green lighten-1" style="margin-right: 10px;margin-left: 5px" v-if="
                  itemCh.action === 'created' || itemCh.action === 'opened'
                ">fa-plus-square-o</v-icon>
              <!-- 删除/取消-->
              <v-icon middle color="red lighten-1" style="margin-right: 10px;margin-left: 5px" v-else-if="
                  itemCh.action === 'erased' ||
                    itemCh.action === 'deleted' ||
                    itemCh.action === 'deletedfile' ||
                    itemCh.action === 'canceled' ||
                    itemCh.action === 'closed'
                ">fa-remove</v-icon>
              <!-- 开始/继续-->
              <v-icon middle color="teal darken-1" style="margin-right: 10px;margin-left: 5px" v-else-if="itemCh.action === 'started'|| itemCh.action === 'restarted'">fa fa-play-circle-o</v-icon>
              <!-- 激活-->
              <v-icon middle color="green" style="margin-right: 10px;margin-left: 5px" v-else-if="itemCh.action === 'activated'">fa fa-arrows</v-icon>
              <!-- 指派-->
              <v-icon middle color="teal lighten-1" style="margin-right: 10px;margin-left: 5px" v-else-if="itemCh.action === 'assigned'">fa fa-location-arrow</v-icon>
              <!-- 暂停-->
              <v-icon middle color="deep-purple darken-1" style="margin-right: 10px;margin-left: 5px" v-else-if="itemCh.action === 'paused'">fa-pause-circle-o</v-icon>
              <!-- 完成-->
              <v-icon middle color="green lighten-1" style="margin-right: 10px;margin-left: 5px" v-else-if="itemCh.action === 'finished'">fa-recycle</v-icon>
              <!-- 其他-->
              <v-icon middle color="light-blue darken-1" style="margin-right: 10px;margin-left: 5px" v-else>fa-edit</v-icon>

              <a class="event-created-at">{{ itemCh.date }}</a>
              <span class="event-actor">
                <a class="link-member" data-stack="true">{{
                  itemCh.actortext
                }}</a>
              </span>
              <!--              <span class="event-action">{{ getActionText(itemCh.action) }}</span>-->
              <span class="event-action">{{ itemCh.actiontext }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
    import {Component, Prop, Vue} from "vue-property-decorator";
    import ActionService from "@service/action/action-service";
    import {Environment} from "@/environments/environment";
    import CodeListService from "@codelist/codelist-service";

    @Component({})
export default class AppTaskActiondata extends Vue {

    /**
     * 视图参数
     *
     * @type {*}
     * @memberof AppTaskActiondata
     */
    @Prop() public viewparams!: any;

    /**
     * 视图上下文
     *
     * @type {*}
     * @memberof AppTaskActiondata
     */
    @Prop() public context!: any;

    /**
     * action的数组记录
     *
     * @type {Array<*>}
     * @memberof AppTaskActiondata
     */
    @Prop() public items: any;

    /**
     * action的content记录
     *
     * @type {Array<*>}
     * @memberof AppTaskActiondata
     */
    public actionItems: Array<any> = [];

    /**
     * action的所有内容
     *
     * @type {*}
     * @memberof AppTaskActiondata
     */
    public actiondata: any;

    /**
     * 调用获取action记录的url
     *
     * @type {string}
     * @memberof AppTaskActiondata
     */
    public actionUrl: string = "actions/searchdefault";

    /**
     * 是否正在编辑 action的编辑状态
     *
     * @type {Array<boolean>}
     * @memberof AppTaskActiondata
     */
    public isCommentedItemEdit: Array<boolean> = [];

    /**
     * 临时变量，用于存储action评论 修改的值
     *
     * @type {Array<*>}
     * @memberof AppTaskActiondata
     */
    public tempActionRichtextContent: Array<string> = [];

    /**
     * 显示的action记录
     *
     * @type {Array<*>}
     * @memberof AppTaskActiondata
     */
    public actionShowItems: Array<any> = [];

    /**
     * 是否显示更多的action动态
     *
     * @type {Array<boolean>}
     * @memberof AppTaskActiondata
     */
    public isShowMoreAction: Array<boolean> = [];

    /**
     * 上传路径
     *
     * @type {string}
     * @memberof UploadFile
     */
    public uploadUrl: string = Environment.BaseUrl + Environment.UploadFile;

    /**
     * 下载路径
     *
     * @type {string}
     * @memberof DownloadFile
     */
    public exportFileUrl: string = Environment.BaseUrl + Environment.ExportFile;

    /**
     * action的service
     *
     * @type {ActionService}
     * @memberof AppTaskActiondata
     */
    public activeService: ActionService = new ActionService();

    /**
     * 分页对象
     *
     * @type {*}
     * @memberof AppTaskActiondata
     */
    private page: object = {
        size: 1000,
        page: 0,
    };

    /**
     * 代码表服务对象
     *
     * @type {CodeListService}
     * @memberof AppTaskActiondata
     */
    public codeListService: CodeListService = new CodeListService({
        $store: this.$store,
    });

    /**
     * 全部用户信息
     *
     * @type {Array<*>}
     * @memberof AppTaskActiondata
     */
    public userslist: Array<any> = [];

    /**
     * Vue声明周期
     *
     * @memberof AppTaskActiondata
     */
    public created() {
    }

    /**
     * Vue声明周期，组件挂载完毕
     *
     * @memberof TaskActionBase
     */
    public mounted() {
        // console.log(this.items)
        this.actionItems = this.items;

        let taskId = this.context.task;
        if (!taskId) {
            taskId = this.viewparams.taskId;
        }
        if (taskId) {
            // 获取用户代码表
            this.getUserCodeList(taskId);
        }
    }

    /**
     * 获取动态代码表UserRealName
     *
     * @param {string} [taskId] 任务id
     * @memberof AppTaskActiondata
     */
    public async getUserCodeList(taskId: string) {
        let codeList: any = this.codeListService.getItems("UserRealName");
        await codeList
            .then((items: any) => {
                if (items && items.length > 0) {
                    this.userslist.push(...items);
                }
                // 整理数据
                this.organizeActionData();
            })
            .catch((error: any) => {
                console.log(error);
            });
    }

    /**
     * 代码表转换
     *
     * @param {*} [action] 当前动作
     * @memberof AppTaskActiondata
     */
    public getActionText(action: string) {
        let actionTypeCodelist: any = this.getAction__typeCodelist();
        let text = "";
        for (let i = 0; i < actionTypeCodelist.length; i++) {
            if (actionTypeCodelist[i].id == action) {
                text = actionTypeCodelist[i].label;
            }
        }
        return text;
    }

    /**
     * 获取代码表
     *
     * @return {Array<*>}
     * @memberof AppTaskActiondata
     */
    public getAction__typeCodelist() {
        const codelist = this.$store.getters.getCodeList("Action__type");
        if (codelist) {
            let items: Array<any> = [...JSON.parse(JSON.stringify(codelist.items))];
            return items;
        } else {
            console.log(`----Action__type----代码表不存在`);
            return [];
        }
    }

    /**
     * 评论更新 记录评论区的保存 取消点击
     *
     * @param {*} [state] 评论框状态
     * @param {number} [index] 下标
     * @param {string} [content] 评论内容
     * @memberof AppTaskActiondata
     */
    public itemRichTextClick(state: string, index: number, content: string) {
        if (state == "cancel") {
            for (let i = 0; i < this.isCommentedItemEdit.length; i++) {
                this.isCommentedItemEdit[i] = false;
            }
            this.$forceUpdate();
            // this.tempActionRichtextContent[index] = '';
        } else if (state == "save") {
            console.log("保存记录: " + content);
            this.isCommentedItemEdit[index] = false;
            // 给action富文本编辑器value绑定的actionitem赋值
            this.actionItems[index].comment = this.tempActionRichtextContent[index];
            // let actionRichTextEditor:any = this.$refs['actionRichTextEditor'+index];
            this.$forceUpdate();
            // （不更新） 暂时无法更新，调用会报错 调用接口更新action
            /*return new Promise((resolve: any, reject: any) => {
                          let params: any = {};
                          Object.assign(params, this.actionItems[index]);
                          let context = {action:this.actionItems[index].id};
                          let result: Promise<any> = this.activeService.Update(context, params, true);
                          result.then((response) => {
                              if (response && response.status === 200) {

                              }
                          }).catch(response => {
                              // console.log(response);
                              this.$Notice.error({ title: '错误', desc: response.data.detail });
                              reject(response);
                          });
                      });*/
        }
    }

    /**
     * 右上角操作 关闭|取消
     * @param {string} [command] 指令
     * @param {any} [ell] 点击的元素
     * @memberof AppTaskActiondata
     */
    public handleCommand(command: string, ell: any) {
        if (command == "edit") {
            for (let i = 0; i < this.isCommentedItemEdit.length; i++) {
                this.isCommentedItemEdit[i] = false;
            }
            let index = ell.$attrs.index;
            this.isCommentedItemEdit[index] = true;
            this.$forceUpdate();
        }
    }

    /**
     * 显示更多任务action动态
     *
     * @param {number} [index] 当前评论下标
     * @memberof AppTaskActiondata
     */
    public showMoreAction(index: number) {
        this.isShowMoreAction[index] = true;
        this.$forceUpdate();
    }

    /**
     * 根据任务获取action
     *
     * @param {string} [taskid] 任务id
     * @memberof AppTaskActiondata
     */
    public searchActionByTask(taskId: string) {
        let params: object = {n_objecttype_eq: "task", n_objectid_eq: taskId};
        Object.assign(params, this.page);

        return new Promise((resolve: any, reject: any) => {
            let result: Promise<any>;
            result = this.activeService.searchActionByTask(this.actionUrl, params, true);
            result.then((response) => {
                    if (response && response.status === 200) {
                        if (JSON.stringify(response.data) &&
                            JSON.stringify(response.data).length > 0) {
                            this.actiondata = response.data;
                            this.actionItems = response.data.content;
                            this.organizeActionData();
                        }
                    }
                }).catch((response) => {
                    if (response && response.status === 500) {
                        const url: any = "/500";
                        this.$router.push({path: url});
                    } else {
                        this.$Notice.error({title: "错误", desc: response.data.detail});
                        reject(response);
                    }
                });
        });
    }

    /**
     * 整理action数据
     *
     * @memberof AppTaskActiondata
     */
    public organizeActionData() {
        this.tempActionRichtextContent = new Array<any>(this.actionItems.length);
        for (let i = 0; i < this.actionItems.length; i++) {
            let actionItem = this.actionItems[i];
            // 修改action的值
            if(actionItem.actiontype){
                actionItem.action = actionItem.actiontype;
            }
            this.userslist.forEach((useritme: any) => {
                if (Object.is(useritme.value, actionItem.actor)) {
                    actionItem.actortext = useritme.label;
                }
            });
        }
        // 记录是否在编辑状态
        this.isCommentedItemEdit = new Array<any>(this.actionItems.length);
        // 是否显示更多的action动态
        this.isShowMoreAction = new Array<any>(this.actionItems.length);
        // 非评论记录
        let nonCommentAction: Array<any> = [];
        // 每次加载清空数据
        this.actionShowItems = [];
        for (let i = 0; i < this.actionItems.length; i++) {
            this.isCommentedItemEdit[i] = false;
            this.isShowMoreAction[i] = false;
            // 当前是非评论记录，上一条也不是评论记录
            if (
                i > 0 &&
                this.actionItems[i].action !== "commented" &&
                this.actionItems[i - 1].action !== "commented"
            ) {
                nonCommentAction.push(this.actionItems[i]);
            } else {
                // 非评论记录多条时，且不满足（当前是非评论记录，上一条也不是评论记录）
                if (nonCommentAction.length > 0) {
                    this.actionShowItems.push(nonCommentAction);
                    nonCommentAction = [];
                }
                // 当前是非评论记录
                else if (this.actionItems[i].action !== "commented") {
                    this.actionShowItems.push(this.actionItems[i]);
                }
            }
            // 评论记录
            if (this.actionItems[i].action === "commented") {
                const url = this.exportFileUrl.indexOf("../") === 0
                        ? this.exportFileUrl.substring(3)
                        : this.exportFileUrl;
                this.actionItems[i].comment = this.actionItems[i].comment.replace(
                    /\{(\d+)\.(bmp|jpg|jpeg|png|tif|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF|webp)\}/g,
                    `${url}/$1`);
                this.actionShowItems.push(this.actionItems[i]);
            }
        }
        // 遍历完成时
        if (nonCommentAction.length > 0) {
            this.actionShowItems.push(nonCommentAction);
            nonCommentAction = [];
        }
    }


}
</script>

<style lang="less">
@import "./app-task-actiondata.less";
</style>
